package com.hnhuas.salary.modules.admin.controller;

import com.hnhuas.salary.common.BaseController;
import com.hnhuas.salary.common.utils.R;
import com.hnhuas.salary.modules.admin.entity.SalaryUserEntity;
import com.hnhuas.salary.modules.admin.form.PasswordForm;
import com.hnhuas.salary.modules.admin.form.SysLoginForm;
import com.hnhuas.salary.modules.admin.service.SalaryUserService;
import com.wangfan.endecrypt.utils.EndecryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.wf.jwtp.provider.Token;
import org.wf.jwtp.provider.TokenStore;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by weirdor on 2019-08-23 19:06
 */
@RestController
@RequestMapping("/")
public class MainController extends BaseController {

    @Autowired
    private SalaryUserService userService;

    @Autowired
    private TokenStore tokenStore;


    /**
     * 登录
     */
    @PostMapping("/login")
    public R login(@RequestBody SysLoginForm form) {
        //用户信息
        SalaryUserEntity user = userService.queryByUserName(form.getUsername());

        List<String> stringList=new ArrayList<>();

        if (user == null) {
            return R.error("账号不存在");
        } else if (!user.getPassword().equals(EndecryptUtils.encrytMd5(form.getPassword()))) {

//        } else if (!user.getPassword().equals(form.getPassword())) {
            return R.error("密码错误");
        }
        if (user.getIsAdmin()){
            stringList.add("admin");
        }
        String[] strings = new String[stringList.size()];
        // 签发token
        Token token = tokenStore.createNewToken(String.valueOf(user.getId()),  null, stringList.toArray(strings));

        Map<String,Object> map=new HashMap<>();
        map.put("access_token",token.getAccessToken());
        map.put("is_admin",user.getIsAdmin());

        return R.ok("登录成功").put("data",map);
    }

    /**
     * 获取当前登录用户信息
     * @param request
     * @return
     */
    @GetMapping("/info")
    public R userInfo(HttpServletRequest request) {
        SalaryUserEntity user = userService.getById(getLoginUserId(request));
        return R.ok().put("data", user);
    }

    /**
     * 修改当前用户密码
     * @param
     * @return
     */
    @PutMapping("/psw")
    public R updatePsw(@RequestBody PasswordForm passwordForm, HttpServletRequest request) {
        if (!EndecryptUtils.encrytMd5(passwordForm.getPassword()).equals(userService.getById(getLoginUserId(request)).getPassword())) {
            return R.error("原密码不正确");
        }
        SalaryUserEntity user = new SalaryUserEntity();
        user.setId(getLoginUserId(request));
        user.setPassword(EndecryptUtils.encrytMd5(passwordForm.getNewPassword()));
        if (userService.updateById(user)) {
            return R.ok("修改成功");
        }
        return R.error("修改失败");
    }



}
